import air.update.ApplicationUpdaterUI;
import air.update.events.UpdateEvent;

import com.projectcocoon.twit.view.About;
import com.projectcocoon.twit.view.Chatroom;

import flash.desktop.NativeApplication;
import flash.display.NativeWindow;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.SharedObject;
import flash.utils.Timer;

import mx.core.UIComponent;
import mx.events.ResizeEvent;

private var overlay:UIComponent;
private var rightClickMenu:ContextMenu;
private var videoMenu:NativeMenu;
private var interactiveMenu:NativeMenu;
private var chatroomWindow:Chatroom;
private var aboutWindow:About;

private var updater:ApplicationUpdaterUI;
private var preferences:SharedObject;

private function init():void
{
	loadPreferences();
	drawOverlay();
	createRightClick();
	checkForUpdates();
	
	nativeWindow.addEventListener(Event.CLOSING, onExit);
	nativeWindow.addEventListener(Event.DEACTIVATE, setFramerate);
	stage.addEventListener(ResizeEvent.RESIZE, drawOverlay);
	addEventListener(Event.ENTER_FRAME, setFramerate);
}

private function setFramerate(evt:Event):void
{
	stage.frameRate = 31;
}

private function checkForUpdates():void
{
	updater = new ApplicationUpdaterUI();
	updater.configurationFile = new File("app:/xml/updateConfig.xml");
	updater.addEventListener(UpdateEvent.INITIALIZED, onUpdateInitialized);
	updater.initialize();
	
	Settings.CHECK_UPDATES.addEventListener(Event.SELECT, onUpdateCheck);
}

private function onUpdateInitialized(evt:Event):void
{
	updater.isCheckForUpdateVisible = false;
	updater.checkNow();
}

private function onUpdateCheck(evt:Event):void 
{
	updater.isCheckForUpdateVisible = true;
	updater.checkNow();
}

private function onExit(evt:Event):void
{
	savePreferences();
	evt.preventDefault();
	for each(var win:NativeWindow in NativeApplication.nativeApplication.openedWindows) {
		win.close();
	}
	NativeApplication.nativeApplication.exit();
}

private function loadPreferences():void
{	
	preferences = SharedObject.getLocal("twitlivedesktop");
	var t:Timer = new Timer(100,1);
	t.addEventListener(TimerEvent.TIMER, function():void {
		if(preferences.data.alwaysOnTop) {
			Settings.ALWAYS_ON_TOP.checked = true;
			nativeWindow.alwaysInFront = true;
		} else {
			Settings.ALWAYS_ON_TOP.checked = false;
			nativeWindow.alwaysInFront = false;
		}
		if(preferences.data.preferredStream) {
			switch(preferences.data.preferredStream) {
				case Settings.VIDEO_JUSTIN.caption:
					Settings.VIDEO_JUSTIN.checked = true;
					video.location = Settings.JUSTIN_TV_1MBPS;
				break;
				case Settings.VIDEO_BITGRAVITY_400KBPS.caption:
					Settings.VIDEO_BITGRAVITY_400KBPS.checked = true;
					video.location = Settings.BITGRAVITY_400KBPS;
				break;
				case Settings.VIDEO_BITGRAVITY_1MBPS.caption:
					Settings.VIDEO_BITGRAVITY_1MBPS.checked = true;
					video.location = Settings.BITGRAVITY_1MBPS;
				break;
				case Settings.VIDEO_USTREAM.caption:
					Settings.VIDEO_USTREAM.checked = true;
					video.location = Settings.USTREAM_500KPBS;
				break;
				case Settings.VIDEO_AUDIO_ONLY.caption:
					Settings.VIDEO_AUDIO_ONLY.checked = true;
					video.location = Settings.AUDIO_ONLY;
				break;
				default:
					video.location = Settings.DEFAULT_VIDEO_STREAM;
					Settings.VIDEO_JUSTIN.checked = true;
				break;
			}
			
		} else {
			video.location = Settings.DEFAULT_VIDEO_STREAM;
			Settings.VIDEO_JUSTIN.checked = true;
		}
		
	});
	
	if(preferences.data.windowWidth && preferences.data.windowHeight && preferences.data.left && preferences.data.top) {
		nativeWindow.width = preferences.data.windowWidth;
		nativeWindow.height = preferences.data.windowHeight;
		nativeWindow.x = preferences.data.left;
		nativeWindow.y = preferences.data.top;
	} else {
		nativeWindow.width = Settings.DEFAULT_WINDOW_WIDTH;
		nativeWindow.height = Settings.DEFAULT_WINDOW_HEIGHT;
	}
	
	t.start();
}

private function savePreferences():void
{
	preferences = SharedObject.getLocal("twitlivedesktop");
	preferences.data.alwaysOnTop = Settings.ALWAYS_ON_TOP.checked;

	if(Settings.VIDEO_JUSTIN.checked == true) preferences.data.preferredStream = Settings.VIDEO_JUSTIN.caption;
	if(Settings.VIDEO_BITGRAVITY_400KBPS.checked == true) preferences.data.preferredStream = Settings.VIDEO_BITGRAVITY_400KBPS.caption;
	if(Settings.VIDEO_BITGRAVITY_1MBPS.checked == true) preferences.data.preferredStream = Settings.VIDEO_BITGRAVITY_1MBPS.caption;
	if(Settings.VIDEO_USTREAM.checked == true) preferences.data.preferredStream = Settings.VIDEO_USTREAM.caption;
	if(Settings.VIDEO_AUDIO_ONLY.checked == true) preferences.data.preferredStream = Settings.VIDEO_AUDIO_ONLY.caption;

	if(stage.displayState != StageDisplayState.FULL_SCREEN) {
		preferences.data.windowWidth = nativeWindow.width;
		preferences.data.windowHeight = nativeWindow.height;
		preferences.data.top = nativeWindow.y;
		preferences.data.left = nativeWindow.x;
	}
}


private function drawOverlay(evt:Event=null):void
{
	if(!overlay) {
		overlay = new UIComponent();
		overlay.doubleClickEnabled = true;
		overlay.addEventListener(MouseEvent.DOUBLE_CLICK, onToggleFullscreen);
	}
	overlay.graphics.clear();
	overlay.graphics.beginFill(0x000000,0.05);
	overlay.graphics.drawRect(0,0,stage.stageWidth,stage.stageHeight);
	overlay.graphics.endFill();		
	addElement(overlay);
}

private function onToggleFullscreen(evt:Event):void
{
	if(stage.displayState == StageDisplayState.FULL_SCREEN) {
		stage.displayState = StageDisplayState.NORMAL;
	} else {
		stage.displayState = StageDisplayState.FULL_SCREEN;
	}
}

private function createRightClick():void
{			
	Settings.ALWAYS_ON_TOP.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, toggleAlwaysOnTop);
	Settings.ABOUT_TWIT_LIVE.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onAbout);
	
	rightClickMenu = new ContextMenu();
	
	rightClickMenu.addItem(Settings.SNAPSHOT);
	Settings.SNAPSHOT.addEventListener(Event.SELECT, onSnapshot);
	
	videoMenu = new NativeMenu();
	videoMenu.addEventListener(Event.SELECT, onVideoSourceChange);
	
	videoMenu.addItem(Settings.VIDEO_JUSTIN);
	videoMenu.addItem(Settings.VIDEO_BITGRAVITY_400KBPS);
	videoMenu.addItem(Settings.VIDEO_BITGRAVITY_1MBPS);
	videoMenu.addItem(Settings.VIDEO_USTREAM);
	videoMenu.addItem(Settings.VIDEO_AUDIO_ONLY);
	
	interactiveMenu = new NativeMenu();
	interactiveMenu.addEventListener(Event.SELECT, onInteractiveSelected);
	
	interactiveMenu.addItem(Settings.CHATROOM);
	interactiveMenu.addItem(Settings.TWIT_ARMY);
	interactiveMenu.addItem(Settings.TWITTER);
	interactiveMenu.addItem(Settings.LEOVILLE);
	interactiveMenu.addItem(Settings.SCHEDULE);
	interactiveMenu.addItem(Settings.TIP_LEO);
	
	rightClickMenu.addSubmenu(videoMenu, "Change video source");
	rightClickMenu.addSubmenu(interactiveMenu, "TWiT interactive");
	rightClickMenu.addItem(Settings.CHECK_UPDATES);
	rightClickMenu.addItem(Settings.ALWAYS_ON_TOP);
	rightClickMenu.addItem(Settings.ABOUT_TWIT_LIVE);
	
	overlay.contextMenu = rightClickMenu;
}

private function onSnapshot(evt:Event):void
{
	var snapshotBitmapData:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);
	snapshotBitmapData.draw(video);
	
	var encoder:JPEGEncoder = new JPEGEncoder();
	var jpegEncoder:ByteArray = encoder.encode(snapshotBitmapData);
	
	var jpegFile:File = File.applicationStorageDirectory.resolvePath("snapshot.jpg");

	var jpegFileStream:FileStream = new FileStream();
	jpegFileStream.open(jpegFile, FileMode.WRITE);
	jpegFileStream.writeBytes(jpegEncoder);
	jpegFileStream.close();
	
	if(stage.displayState == StageDisplayState.FULL_SCREEN) stage.displayState = StageDisplayState.NORMAL;
	
	jpegFile.openWithDefaultApplication();			
}

private function onAbout(evt:Event):void
{
	if(aboutWindow) aboutWindow.close();
	aboutWindow = new About();
	aboutWindow.open();
}

private function onVideoSourceChange(evt:Event):void
{
	Settings.VIDEO_JUSTIN.checked = false;
	Settings.VIDEO_BITGRAVITY_400KBPS.checked = false;
	Settings.VIDEO_BITGRAVITY_1MBPS.checked = false;
	Settings.VIDEO_USTREAM.checked = false;
	Settings.VIDEO_AUDIO_ONLY.checked = false;
	
	var item:ContextMenuItem = ContextMenuItem(evt.target);
	
	switch(item.caption) {
		case Settings.VIDEO_JUSTIN.caption:
			Settings.VIDEO_JUSTIN.checked = true;
			video.location = Settings.JUSTIN_TV_1MBPS;
			break;
		case Settings.VIDEO_BITGRAVITY_400KBPS.caption:
			Settings.VIDEO_BITGRAVITY_400KBPS.checked = true;
			video.location = Settings.BITGRAVITY_400KBPS;
			break;
		case Settings.VIDEO_BITGRAVITY_1MBPS.caption:
			Settings.VIDEO_BITGRAVITY_1MBPS.checked = true;
			video.location = Settings.BITGRAVITY_1MBPS;
			break;						
		case Settings.VIDEO_USTREAM.caption:
			Settings.VIDEO_USTREAM.checked = true;
			video.location = Settings.USTREAM_500KPBS;
			break;							
		case Settings.VIDEO_AUDIO_ONLY.caption:
			Settings.VIDEO_AUDIO_ONLY.checked = true;
			video.location = Settings.AUDIO_ONLY;
			break;
	}
}

private function onInteractiveSelected(evt:Event):void
{
	var item:ContextMenuItem = ContextMenuItem(evt.target);
	
	switch(item.caption) {
		case Settings.CHATROOM.caption:
			if(chatroomWindow) chatroomWindow.close();
			chatroomWindow = new Chatroom();
			chatroomWindow.open();
			break;
		case Settings.TWIT_ARMY.caption:
			navigateToURL(new URLRequest(Settings.TWIT_ARMY_LINK),"_blank");
			break;
		case Settings.TWITTER.caption:
			navigateToURL(new URLRequest(Settings.TWITTER_LINK),"_blank");
			break;
		case Settings.LEOVILLE.caption:
			navigateToURL(new URLRequest(Settings.LEOVILLE_LINK),"_blank");
			break;
		case Settings.SCHEDULE.caption:
			navigateToURL(new URLRequest(Settings.SCHEDULE_LINK),"_blank");
			break;
		case Settings.TIP_LEO.caption:
			navigateToURL(new URLRequest(Settings.TIP_LEO_LINK),"_blank");
			break;
	}
}

private function toggleAlwaysOnTop(evt:Event):void
{
	if(Settings.ALWAYS_ON_TOP.checked == false) {
		nativeWindow.alwaysInFront = true;
		Settings.ALWAYS_ON_TOP.checked = true;
	} else {
		nativeWindow.alwaysInFront = false;
		Settings.ALWAYS_ON_TOP.checked = false;
	}
	savePreferences();
}